package com.siwei.mes.service.laboratory.factory.material.cement;

import com.alibaba.fastjson.JSONObject;
import com.siwei.mes.common.util.JsonUtils;
import com.siwei.mes.common.util.NullUtils;
import com.siwei.mes.entity.experiment.CheckBatchConfig;
import com.siwei.mes.entity.experiment.Experiment;
import com.siwei.mes.entity.experiment.ExperimentDetail;
import com.siwei.mes.entity.experiment.cement.CementBbmj;
import com.siwei.mes.entity.laboratory.DataDefaultUc;
import com.siwei.mes.entity.laboratory.cement.DataSnBbmj;
import com.siwei.mes.entity.system.TestProjectInfo;
import com.siwei.mes.entity.system.TestProjectSpecConfig;
import com.siwei.mes.enums.TestProjectEnum;
import com.siwei.mes.mapper.experiment.ExperimentDetailMapper;
import com.siwei.mes.mapper.laboratory.CementLaboratoryMapper;
import com.siwei.mes.mapper.laboratory.UploadLaboratoryMapper;
import com.siwei.mes.service.laboratory.factory.LaboratoryAbstractService;
import com.siwei.mes.service.laboratory.factory.entity.LaboratoryDownloadVo;
import com.siwei.mes.service.laboratory.factory.material.MaterialLaboratoryFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 水泥-比表面积
 *
 * @Description: 水泥-比表面积
 * @Version: 1.0
 * @author: mlchen
 * @date: 2025/3/29 17:22
 */
@Service
public class CementBbmjFactory extends LaboratoryAbstractService implements MaterialLaboratoryFactory {
    private static final Logger log = LoggerFactory.getLogger("laboratory");

    @Resource
    private CementLaboratoryMapper cementLaboratoryMapper;
    @Resource
    private UploadLaboratoryMapper uploadLaboratoryMapper;
    @Resource
    private ExperimentDetailMapper experimentDetailMapper;

    private final TestProjectEnum testProjectEnum = TestProjectEnum.CEMENT_PARAM_BBMJ;

    @Override
    public void processUpload(JSONObject objJson, String sampleNo, Experiment experiment, List<CheckBatchConfig> batchConfigList, List<TestProjectInfo> testProjectInfoList, List<TestProjectSpecConfig> testProjectSpecConfigList, ExperimentDetail detail, String samId) {
        log.info("开始上传到协会数据库：【水泥-{}】", testProjectEnum.getName());
        CementBbmj cementBbmj = objJson.toJavaObject(CementBbmj.class);
        if (cementBbmj == null) {
            log.info("水泥-【{}】数据为空，跳过上传！objJson：{}", testProjectEnum.getName(), objJson);
            return;
        }
        DataSnBbmj dataSnBbmj = new DataSnBbmj();
        dataSnBbmj.setS26(NullUtils.ifNull(cementBbmj.getPjz()));

        List<CementBbmj.Bbmjcsy> bbdycsy = cementBbmj.getBbmjsy();
        int con = 1;
        for (CementBbmj.Bbmjcsy bbmj : bbdycsy) {
            if (con == 1) {
                dataSnBbmj.setS5(NullUtils.ifNull(bbmj.getBzypbbmj()));
                dataSnBbmj.setS6(NullUtils.ifNull(bbmj.getBzypmd()));
                dataSnBbmj.setS7(NullUtils.ifNull(bbmj.getBzypkxl()));
                dataSnBbmj.setS8(NullUtils.ifNull(bbmj.getBzypymjlsj()));
                dataSnBbmj.setS9(NullUtils.ifNull(bbmj.getBcypkxl()));
                dataSnBbmj.setS10(NullUtils.ifNull(bbmj.getBcypmd()));
                dataSnBbmj.setS11(NullUtils.ifNull(bbmj.getBcypymjlsj()));
                dataSnBbmj.setS12(NullUtils.ifNull(bbmj.getBcypbbmj()));
            } else if (con == 2) {
                dataSnBbmj.setS17(NullUtils.ifNull(bbmj.getBzypbbmj()));
                dataSnBbmj.setS18(NullUtils.ifNull(bbmj.getBzypmd()));
                dataSnBbmj.setS19(NullUtils.ifNull(bbmj.getBzypkxl()));
                dataSnBbmj.setS20(NullUtils.ifNull(bbmj.getBzypymjlsj()));
                dataSnBbmj.setS21(NullUtils.ifNull(bbmj.getBcypkxl()));
                dataSnBbmj.setS22(NullUtils.ifNull(bbmj.getBcypmd()));
                dataSnBbmj.setS23(NullUtils.ifNull(bbmj.getBcypymjlsj()));
                dataSnBbmj.setS24(NullUtils.ifNull(bbmj.getBcypbbmj()));
            }
            con++;
        }

        //获取标准值
        for (CheckBatchConfig projectInfo : batchConfigList) {
            if (projectInfo.getTestProjectCode() != null && projectInfo.getTestProjectCode().equals(TestProjectEnum.CEMENT_PARAM_BBMJ.getCode())) {
                dataSnBbmj.setSt1(NullUtils.ifNull(projectInfo.getCheckValueUnit()));
            }
        }

        //设置公共属性
        super.setCommonProperties(sampleNo, experiment, dataSnBbmj, "水泥", cementBbmj.getJcrq(), detail);

        //根据样品编码查询水泥比表面积
        DataSnBbmj data_jgcl_sn_bzcdnjsjBySampleNo = cementLaboratoryMapper.findDATA_JGCL_SN_XD_BBMJBySampleNo(sampleNo);
        //查询没值说明需要  新增水泥比表面积
        if (data_jgcl_sn_bzcdnjsjBySampleNo == null) {
            cementLaboratoryMapper.addDATA_JGCL_SN_XD_BBMJ(dataSnBbmj);
        } else {
            //修改水泥比表面积
            cementLaboratoryMapper.updateDATA_JGCL_SN_XD_BBMJ(dataSnBbmj);
        }


        //赋值dateDefalutUC
        //存储协会需要做的项目集合
        Set<String> set = new HashSet<>();

        for (TestProjectInfo testProjectInfo : testProjectInfoList) {
            if (detail.getTestProjectCode() != null && testProjectInfo.getTestCode() != null && testProjectInfo.getTestCode().equals(detail.getTestProjectCode())) {
                if (testProjectInfo.getParameterName() != null && !testProjectInfo.getParameterName().isEmpty()) {
                    //添加进协会需要做的项目集合
                    set.addAll(Arrays.asList(testProjectInfo.getParameterName().split(",")));
                }
            }
        }

        for (String str : set) {
            DataDefaultUc defaultUc = new DataDefaultUc();

            Map<String, Object> itemParameter = uploadLaboratoryMapper.findItemParameter(str, samId);

            if (itemParameter == null || itemParameter.get("ParameterID") == null) {
                log.error("未查询到对应的材料：value = " + str + "SampleID =" + samId);
                continue;
            }
            String parameterID = itemParameter.get("ParameterID").toString();

            String jcrq = cementBbmj.getJcrq();

            defaultUc.setConclusion(cementBbmj.getDxjl());
            defaultUc.setUcResultValue(cementBbmj.getDxjl());
            defaultUc.setUcTestValue(cementBbmj.getPjz());


            //获取标准值
            for (CheckBatchConfig projectInfo : batchConfigList) {
                if (projectInfo.getTestProjectCode() != null && projectInfo.getTestProjectCode().equals(TestProjectEnum.CEMENT_PARAM_BBMJ.getCode())) {
                    defaultUc.setUcUnit(NullUtils.ifNull(projectInfo.getCheckValueUnit()));
                }
            }


            //根据物料信息设置判断配置
            for (TestProjectSpecConfig test : testProjectSpecConfigList) {
                if (TestProjectEnum.CEMENT_PARAM_BBMJ.getCode().equals(test.getTestProjectCode())) {
                    if (experiment.getMaterialsName() != null && experiment.getMaterialsSpecs() != null && experiment.getMaterialsName().equals(test.getMaterialsName()) && experiment.getMaterialsSpecs().equals(test.getMaterialsSpec())) {
                        String json = test.getObjJson();
                        super.setUcStandardValue(defaultUc, json, "bbmj");
                    }
                }
            }

            //赋值
            super.setDefUc(defaultUc, experiment, "水泥检测室", sampleNo, jcrq, detail);

            defaultUc.setUcParameterID(parameterID);//项目id
            //新增或修改DataDefaultUc
            super.insertOrUpdateDataDefaultUc(sampleNo, parameterID, defaultUc);

        }
    }

    @Override
    public LaboratoryDownloadVo processDownload(String sampleNo, Experiment experiment, ExperimentDetail detail, Map<String, String> parameterMap, String samId, List<TestProjectInfo> testProjectInfoList) {
        log.info("开始下载协会数据到品控：【水泥-{}】", testProjectEnum.getName());
        JSONObject objJson = detail.getObjJson();
        CementBbmj cementBbmj = objJson.toJavaObject(CementBbmj.class);
        if (cementBbmj == null) {
            log.info("【{}】数据为空，跳过下载！objJson：{}", testProjectEnum.getName(), objJson);
            return null;
        }

        //根据样品编码查询水泥比表面积
        DataSnBbmj data = cementLaboratoryMapper.findDATA_JGCL_SN_XD_BBMJBySampleNo(sampleNo);
        if (data == null) {
            log.info("根据样品编码查询协会比表面积信息为空，跳过下载！sampleNo：{}", sampleNo);
            return null;
        }

        if (data.getDetectonDate() != null) {
            Date detectonDate = data.getDetectonDate();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String strDate = sdf.format(detectonDate);
            cementBbmj.setJcrq(strDate);
        }

        if (data.getConclusion() != null) {
            cementBbmj.setDxjl(data.getConclusion());
        }
        if (data.getS26() != null) {
            cementBbmj.setPjz(data.getS26());
        }

        List<CementBbmj.Bbmjcsy> bbdycsy = cementBbmj.getBbmjsy();
        int con = 1;
        for (CementBbmj.Bbmjcsy bbmj : bbdycsy) {
            if (con == 1) {
                if (data.getS5() != null) {
                    bbmj.setBzypbbmj(data.getS5());
                }
                if (data.getS6() != null) {
                    bbmj.setBzypmd(data.getS6());
                }
                if (data.getS7() != null) {
                    bbmj.setBzypkxl(data.getS7());
                }
                if (data.getS8() != null) {
                    bbmj.setBzypymjlsj(data.getS8());
                }
                if (data.getS9() != null) {
                    bbmj.setBcypkxl(data.getS9());
                }
                if (data.getS10() != null) {
                    bbmj.setBcypmd(data.getS10());
                }
                if (data.getS11() != null) {
                    bbmj.setBcypymjlsj(data.getS11());
                }
                if (data.getS12() != null) {
                    bbmj.setBcypbbmj(data.getS12());
                }

            } else if (con == 2) {
                if (data.getS17() != null) {
                    bbmj.setBzypbbmj(data.getS17());
                }
                if (data.getS18() != null) {
                    bbmj.setBzypmd(data.getS18());
                }
                if (data.getS19() != null) {
                    bbmj.setBzypkxl(data.getS19());
                }
                if (data.getS20() != null) {
                    bbmj.setBzypymjlsj(data.getS20());
                }
                if (data.getS21() != null) {
                    bbmj.setBcypkxl(data.getS21());
                }
                if (data.getS22() != null) {
                    bbmj.setBcypmd(data.getS22());
                }
                if (data.getS23() != null) {
                    bbmj.setBcypymjlsj(data.getS23());
                }
                if (data.getS24() != null) {
                    bbmj.setBcypbbmj(data.getS24());
                }

            }
            con++;
        }
        //对象转json
        JSONObject jsonObject = JsonUtils.beanToObject(cementBbmj);

        //重新赋值
        detail.setObjJson(jsonObject);

        detail.setEquipment(NullUtils.ifNull(data.getEquipment()));
        detail.setTemperature(NullUtils.ifNull(data.getTemperature()));
        detail.setHumidness(NullUtils.ifNull(data.getHumidity()));
        detail.setExperimentGist(NullUtils.ifNull(data.getDetectonRuleCode()));
        detail.setJudgeGist(NullUtils.ifNull(data.getAccessRuleCode()));

        if (parameterMap != null && parameterMap.get(detail.getTestProjectCode()) != null) {
            detail.setStatus(parameterMap.get(detail.getTestProjectCode()));
        }

        //修改品控试验数据
        experimentDetailMapper.updateByPrimaryKeySelective(detail);

        return new LaboratoryDownloadVo().setEquipment(detail.getEquipment())
                .setJudgeGist(detail.getJudgeGist())
                .setExperimentGist(detail.getExperimentGist())
                .setTemperature(detail.getTemperature())
                .setHumidness(detail.getHumidness());
    }
}
